package com.micromall.admin;

import com.github.pagehelper.Page;
import com.google.common.collect.Lists;
import com.micromall.repository.EmployeeMapper;
import com.micromall.repository.EmployeeOrderMapper;
import com.micromall.repository.OrderGoodsMapper;
import com.micromall.repository.entity.Employee;
import com.micromall.repository.entity.Member;
import com.micromall.repository.entity.common.OrderStatus;
import com.micromall.service.MemberService;
import com.micromall.service.TransactionalExecuteService;
import com.micromall.service.vo.ListViewOrder;
import com.micromall.utils.ArgumentValidException;
import com.micromall.utils.Condition.Criteria;
import com.micromall.utils.ValidateUtils;
import com.micromall.web.resp.ResponseEntity;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created by zhangzx on 16/3/28.
 * 提现管理
 */
@RestController
@RequestMapping(value = "/admin/employee")
public class AdminEmployeeController extends AdminBasicController {

	@Resource
	private EmployeeMapper              employeeMapper;
	@Resource
	private EmployeeOrderMapper         employeeOrderMapper;
	@Resource
	private OrderGoodsMapper            orderGoodsMapper;
	@Resource
	private MemberService               memberService;
	@Resource
	private TransactionalExecuteService transactionalExecuteService;

	@RequestMapping(value = "/list")
	@Transactional(readOnly = true)
	public ResponseEntity<?> list() {
		return ResponseEntity.Success(employeeMapper.selectMultiByWhereClause(Criteria.create().andEqualTo("deleted", false).build()));
	}

	@RequestMapping(value = "/search")
	@Transactional(readOnly = true)
	public ResponseEntity<?> search(String query) {
		if (StringUtils.isBlank(query)) {
			return ResponseEntity.Success(Lists.newArrayList());
		}
		return ResponseEntity.Success(employeeMapper.search(query));
	}

	/**
	 * 我的订单列表（包含各种状态的订单）[0:待付款、1:待发货、2:待收货、3:已完成、4:退货/取消]
	 *
	 * @return
	 */
	@RequestMapping(value = "/orders")
	@Transactional(readOnly = true)
	public ResponseEntity<?> orders(int id, @RequestParam(defaultValue = "1") int pageNo, Integer pageSize) {
		Page<ListViewOrder> orders = employeeOrderMapper.selectListViewPageByWhereClause(id, new RowBounds(pageNo, resizeLimit(pageSize)));
		for (ListViewOrder viewOrder : orders) {
			if (viewOrder.getStatus() != OrderStatus.待支付) {
				viewOrder.setTimeoutCloseTime(null);
			}
			viewOrder.setGoodsList(
					orderGoodsMapper.selectMultiByWhereClause(Criteria.create().andEqualTo("order_no", viewOrder.getOrderNo()).build()));
		}
		return ResponseEntity.SuccessPage(orders);
	}

	@RequestMapping(value = "/get")
	@Transactional(readOnly = true)
	public ResponseEntity<?> get(int id) {
		return ResponseEntity
				.Success(employeeMapper.selectOneByWhereClause(Criteria.create().andEqualTo("deleted", false).andEqualTo("id", id).build()));
	}

	private void validateParams(String name, String phone, String scope) {
		if (StringUtils.isBlank(name)) {
			throw new ArgumentValidException("姓名不能为空");
		}
		if (StringUtils.isBlank(phone)) {
			throw new ArgumentValidException("手机号码不能为空");
		}
		if (StringUtils.isBlank(scope)) {
			throw new ArgumentValidException("配送区域不能为空");
		}
		if (ValidateUtils.illegalTextLength(1, 15, name)) {
			throw new ArgumentValidException("姓名长度超过限制");
		}
		if (ValidateUtils.illegalMobilePhoneNumber(phone)) {
			throw new ArgumentValidException("手机号码输入不正确");
		}
		if (ValidateUtils.illegalTextLength(1, 1000, scope)) {
			throw new ArgumentValidException("配送区域长度超过限制");
		}
	}

	/**
	 * @param name 姓名（必填）
	 * @param phone 手机号（必填）
	 * @param weixin 微信号（可以为空）
	 * @param scope 配送区域（必填）
	 * @return
	 */
	@RequestMapping(value = "/add")
	@Transactional
	public ResponseEntity<?> add(String name, String phone, String weixin, String scope) {
		validateParams(name, phone, scope);
		Employee employee = new Employee();
		employee.setName(name);
		employee.setPhone(phone);
		employee.setWeixin(weixin);
		employee.setScope(scope);
		employee.setTimes(0);
		employee.setDeleted(false);
		employee.setCreateTime(new Date());
		transactionalExecuteService.execute(() -> employeeMapper.insert(employee));
		return ResponseEntity.Success();
	}

	@RequestMapping(value = "/update")
	@Transactional
	public ResponseEntity<?> update(int id, String name, String phone, String weixin, String scope) {
		validateParams(name, phone, scope);
		Employee employee = new Employee();
		employee.setId(id);
		employee.setName(name);
		employee.setPhone(phone);
		employee.setWeixin(weixin);
		employee.setScope(scope);
		employee.setUpdateTime(new Date());
		transactionalExecuteService.execute(() -> employeeMapper.updateByPrimaryKey(employee));
		return ResponseEntity.Success();
	}

	@RequestMapping(value = "/delete")
	@Transactional
	public ResponseEntity<?> delete(String ids) {
		if (StringUtils.isBlank(ids)) {
			throw new ArgumentValidException("参数错误");
		}
		transactionalExecuteService.execute(() -> {
			for (String id : ids.split(",")) {
				Employee employee = new Employee();
				employee.setId(Integer.valueOf(id));
				employee.setDeleted(true);
				employee.setUpdateTime(new Date());
				employeeMapper.updateByPrimaryKey(employee);
			}
		});
		return ResponseEntity.Success();
	}

	@RequestMapping(value = "/binding_member")
	@Transactional
	public ResponseEntity<?> binding_member(int employeeId, int memberId) {
		Member member = memberService.get(memberId);
		if (member == null) {
			throw new ArgumentValidException("会员不存在");
		}
		if (employeeMapper.selectOneByWhereClause(Criteria.create().andNotEqualTo("id", employeeId).andEqualTo("uid", memberId).build()) != null) {
			throw new ArgumentValidException("会员已被绑定");
		}

		Employee employee = new Employee();
		employee.setId(employeeId);
		employee.setUid(memberId);
		employee.setUpdateTime(new Date());
		transactionalExecuteService.execute(() -> employeeMapper.updateByPrimaryKey(employee));
		return ResponseEntity.Success();
	}
}
